package com.oscarmovie;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import tt.util.IOUtils;
import tt.util.TimeUtils;

public class MtimeMovie extends Mtime {
	public static void main(String[] args) {
		
		// searchMovieIds();
		// ////////////////////////////////

		// HashMap<String, String> info = searchSingleMovie(50786);System.out.println(info);
		searchAllMovies();

		// ////////////////////////////////

		// HashMap<String, String> images = searchSingleMovieImages(30297);
		// HashMap<String, String> image =
		// searchSingleMovieImage("http://movie.mtime.com/32807/posters_and_images/1211630/");System.out.println(image);

		// searchAllMovieImages();
		// updateName();

	}

	public static void updateName() {
		List<HashMap<Object, Object>> select = Tools.retrieveObjectsWithoutName("movie");
		int size = select.size();
		int i = 0;
		for (HashMap<Object, Object> hm : select) {
			int id = ((BigDecimal) hm.get("ID")).intValue();
			int mtimeId = ((BigDecimal) hm.get("MTIME_ID")).intValue();
			mtimeId = Math.abs(mtimeId);
			System.out.println("============================================================");
			System.out.println("No. " + (++i) + "/" + size + ": " + id + ", " + mtimeId);

			HashMap<String, String> info = searchSingleMovie(mtimeId);

			Tools.updateAlias("movie", id, info.get("name"));

		}
	}

	// ///////////////////////////////////////////////////////////////////////////
	// DOES NOT WORK mtime images ///////////////////////////////////////////
	// ///////////////////////////////////////////////////////////////////////////
	public static void searchAllMovieImages() {
		List<HashMap<Object, Object>> select = Tools.retrieveObjectsWithMtimeIds("movie");
		int size = select.size();
		int i = 0;
		for (HashMap<Object, Object> hm : select) {
			int id = ((BigDecimal) hm.get("ID")).intValue();
			int mtimeId = ((BigDecimal) hm.get("MTIME_ID")).intValue();
			mtimeId = Math.abs(mtimeId);
			System.out.println("============================================================");
			System.out.println("No. " + (++i) + "/" + size + ": " + id + ", " + mtimeId);
			List<HashMap<String, String>> images = searchSingleMovieImages(mtimeId);

			for (HashMap<String, String> info : images) {
				int imageId = Tools.createImage(info.get("thumb"), info.get("name"), info.get("daxiao"),
						info.get("chicun"));
				//Tools.createRelationShip("movie_image", id, imageId);
			}
			if (i > 0)
				break;
		}
	}

	private static List<HashMap<String, String>> searchSingleMovieImages(int mtimeId) {
		List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
		String url = mtimeMovieImages(mtimeId);
		System.out.println("URL: " + url);

		List<String> readFileAsList = IOUtils.readHttpUrlAsList(url, "UTF-8");
		for (String s : readFileAsList) {
			s = s.trim();
			// if(!s.equals(""))System.out.println(s);
			if (s.indexOf("movie_main_l") != -1) {
				// System.out.println(s);
				String pattern = "<div id=\"movie_main\" class=\"mt3 fr\">";
				int p1 = s.indexOf(pattern);
				p1 += pattern.length();
				int p2 = s.indexOf("<div id=\"movie_main_r\" class=\"fr\">", p1);
				String ss = s.substring(p1, p2);

				ss = ss.trim();

				list = parseImages(ss);
				break;
			}
		}
		return list;
	}

	private static HashMap<String, String> searchSingleMovieImage(String url) {
		HashMap<String, String> hm = new HashMap<String, String>();

		System.out.println("URL: " + url);

		List<String> readFileAsList = IOUtils.readHttpUrlAsList(url, "UTF-8");
		for (String s : readFileAsList) {
			s = s.trim();
			if (!s.equals(""))
				System.out.println(s);
			if (s.indexOf("movie_main_l") != -1) {
				// System.out.println(s);
				String pattern = "<div id=\"movie_main\" class=\"mt3 fr\">";
				int p1 = s.indexOf(pattern);
				p1 += pattern.length();
				int p2 = s.indexOf("<div id=\"movie_main_r\" class=\"fr\">", p1);
				String ss = s.substring(p1, p2);

				ss = ss.trim();

				break;
			}
		}
		return hm;
	}

	private static List<HashMap<String, String>> parseImages(String s) {
		List<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();

		String ss = s;
		int p = 0;
		while (true) {
			String start = "<li>";
			String end = "</li>";
			int p1 = ss.indexOf(start, p);
			if (p1 == -1)
				break;
			int p2 = ss.indexOf(end, p1) + end.length();

			// System.out.println("p1: "+p1+", p2: "+p2);
			String anImage = ss.substring(p1, p2);
			System.out.println(anImage);
			HashMap<String, String> parseImage = parseImage(anImage);
			list.add(parseImage);
			p = p2;
		}

		return list;
	}

	private static HashMap<String, String> parseImage(String s) {
		HashMap<String, String> hm = new HashMap<String, String>();
		String ss = s;

		String start = "title=\"";
		String end = "\"";
		String title = Tools.parse(ss, start, end);
		hm.put("name", title);

		start = "<a href=\"";
		end = "\"";
		String origin = Tools.parse(ss, start, end);
		hm.put("origin", origin);

		start = "src=\"";
		end = "\"";
		String thumb = Tools.parse(ss, start, end);
		hm.put("thumb", thumb);

		start = "c_8e\">";
		end = "</p>";
		String chicun = Tools.parse(ss, start, end);
		hm.put("chicun", chicun);

		start = "mt-3\">";
		end = "</p>";
		String daxiao = Tools.parse(ss, start, end);
		hm.put("daxiao", daxiao);

		return hm;
	}

	// ///////////////////////////////////////////////////////////////////////////
	// Search icon image from mtime///////////////////////////////////////////
	// ///////////////////////////////////////////////////////////////////////////
	static List<Integer> list = new ArrayList<Integer>();
	static {
		list.add(155504);
		list.add(100);
		list.add(77882);
	}
	private static boolean isExcluded(int mtimeId){
		return list.contains(mtimeId);
	}
	public static void searchAllMovies() {
		List<HashMap<Object, Object>> select = Tools.retrieveObjectsWithMtimeIds("movie");
		int size = select.size();
		int i = 0;
		for (HashMap<Object, Object> hm : select) {
			int movieId = ((BigDecimal) hm.get("ID")).intValue();
			int mtimeId = ((BigDecimal) hm.get("MTIME_ID")).intValue();
			mtimeId = Math.abs(mtimeId);
			System.out.println("============================================================");
			System.out.println("No. " + (++i) + "/" + size + ": Movie ID: " + movieId + ", Mtime ID: " + mtimeId);
			if (isExcluded(mtimeId))
				continue;
			HashMap<String, String> info = searchSingleMovie(mtimeId);
			System.out.println(info);
			
			int length = 0;
			try {
				length = Integer.parseInt(info.get("length"));
			} catch (Exception e) {

			}
			
			String datetime = info.get("datetime");
			try {
				Date parsedDate = TimeUtils.parseDate(datetime, "yyyy-MM-dd");
				datetime = TimeUtils.getOnlyDate(parsedDate);
			} catch (Exception e) {}
			
			
			
			//Update Movie table/////////////////////////////////////////////////////////////////
			
			
			
//			String nameCn = info.get("name");
//			if(nameCn!=null){
//				Tools.updateMovieNameCn(id, nameCn);
//			}
			
			
			if (length != 0) {
				Tools.updateMtimeLength(length, movieId);
			}
			
			if (datetime != null) {
				Tools.updateMtimeDate(datetime, movieId);
			}
			
			
			int imageId = Tools.createImage(info.get("img"), null, null, null);
			if (imageId != 0) {
				Tools.updateImageId("movie", movieId, imageId);//Update Movie Table
				Tools.updateImage(imageId, "M", movieId);//Update Image table
			}
		}
	}

	private static HashMap<String, String> searchSingleMovie(int mtimeId) {
		HashMap<String, String> hm = new HashMap<String, String>();
		String url = mtimeMovie(mtimeId);
		System.out.println("URL: " + url);

		List<String> readFileAsList = IOUtils.readHttpUrlAsList(url, "UTF-8");
		for (String s : readFileAsList) {
			s = s.trim();
			if (!s.equals("")) {
				// System.out.println(s);
			}
			if (s.indexOf("movie_film_img fl") != -1) {

				String pattern = "<img src=";
				int p1 = s.indexOf(pattern) + pattern.length() + 1;
				int p2 = s.indexOf("\"", p1);
				String ss = s.substring(p1, p2);
				hm.put("img", "" + ss);

			}

			if (s.indexOf("v:itemreviewed") != -1) {
				
				String pattern = "v:itemreviewed\">";
				
				int p1 = s.indexOf(pattern);
				p1 += pattern.length();
				int p2 = s.indexOf("</span>", p1);
				
				String ss = s.substring(p1, p2);
				hm.put("name", "" + ss);

			}

			if (s.indexOf("v:initialReleaseDate") != -1) {
				String pattern = "property=\"v:initialReleaseDate\" content=\"";
				int p1 = s.indexOf(pattern);
				p1 += pattern.length();
				int p2 = s.indexOf("\">", p1);
				String ss = s.substring(p1, p2);
				hm.put("datetime", "" + ss);
			}

			if (s.indexOf("v:runtime") != -1) {
				String pattern = "property=\"v:runtime\" content=\"";
				int p1 = s.indexOf(pattern);
				p1 += pattern.length();
				int p2 = s.indexOf("\">", p1);
				String ss = s.substring(p1, p2);
				ss = ss.replace("分钟", "");
				ss = ss.replace("min", "");
				ss = ss.replace("UK:", "");
				
				ss = ss.split(" ")[0];
				ss = ss.trim();
				hm.put("length", "" + ss);
			}
//			if (s.indexOf("px28 bold hei c_000") != -1) {
//				String pattern = "px28 bold hei c_000";
//				int p1 = s.indexOf(pattern);
//				p1 += pattern.length() + 2;
//				int p2 = s.indexOf("</a>", p1);
//				String ss = s.substring(p1, p2);
//				hm.put("name", "" + ss);
//
//			}
		}
		return hm;
	}

	// ///////////////////////////////////////////////////////////////////////////
	// Search mtime id from baidu ///////////////////////////////////////////
	// ///////////////////////////////////////////////////////////////////////////
	public static void searchMovieIds() {
		List<HashMap<Object, Object>> select = Tools.retrieveMtimeObjects("movie");
		int size = select.size();
		int i = 0;
		for (HashMap<Object, Object> hm : select) {
			// if(i++<10)continue;
			int movieId = ((BigDecimal) hm.get("ID")).intValue();
			String movieName = (String) hm.get("NAME_CN");
			if (movieName == null || movieId == 11236)
				continue;
			System.out.println("No. " + (++i) + "/" + size);

			int mtimeId = searchMovieMtimeId(movieName);
			Tools.updateMovieMtimeId(movieId, mtimeId);
		}
	}

	private static int searchMovieMtimeId(String key) {
		int id = -2;
		String url = baiduMovieMtime(key);
		System.out.println(url);
		List<String> readFileAsList = IOUtils.readHttpUrlAsList(url, "GBK");
		String pattern = "movie.mtime.com/";
		pattern = "www.mtime.com/movie/";
		String i = "";
		for (String s : readFileAsList) {
			int p1 = s.indexOf(pattern);
			if (p1 != -1) {

				try {
					String end = "/";
					i = Tools.parse(s, pattern, end);
					id = Integer.parseInt(i);
				} catch (Exception e) {
					System.out.println("ERR: " + i + ": " + s);
				}
				break;
			}
		}
		System.out.println(id);
		return id;
	}
}
